package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.GroupChatResponseMessage;
import com.netty.chatRoom.message.GroupCreateRequestMessage;
import com.netty.chatRoom.message.GroupCreateResponseMessage;
import com.netty.chatRoom.server.session.Group;
import com.netty.chatRoom.server.session.GroupSession;
import com.netty.chatRoom.server.session.GroupSessionFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;
@ChannelHandler.Sharable
public class GroupCreateRequestMessageHandler extends SimpleChannelInboundHandler<GroupCreateRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupCreateRequestMessage groupCreateRequestMessage) throws Exception {
        // 用户创建群信息
        String createrName = groupCreateRequestMessage.getCreaterName();
        String groupName = groupCreateRequestMessage.getGroupName();
        Set<String> members = groupCreateRequestMessage.getMembers();
        members.add(createrName);
        Group group = GroupSessionFactory.getGroupSession().createGroup(groupName, members);
        if (group==null){// 群已经存在不能再次创建
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(false,String.format("【%s】群已存在，不能创建",groupName)));
        }else {// 群创建成功
            channelHandlerContext.writeAndFlush(new GroupCreateResponseMessage(true,String.format("【%s】群创建成功",groupName)));
            // 给其他成员发送消息
            Set<String> groupMembers = GroupSessionFactory.getGroupSession().getMembers(groupName);
            groupMembers.stream().forEach((member)->{
                if(!member.equals(createrName)){
                    Channel channel = SessionFactory.getSession().getChannel(member);
                    if (channel!=null){
                        channel.writeAndFlush(new GroupCreateResponseMessage(true,String.format("您已被拉进【%s】群聊，创建者【%s】",groupName,createrName)));
                    }
                }
            });
        }
    }
}
